﻿/*
 *  ParameterBase.cs
 *
 *  Copyright (C) 2008 Dreamlusion <dreamlusion@gmail.com>
 *
 *      This program is free software; you can redistribute it and/or
 *      modify it under the terms of the GNU General Public License version
 *      2 as published by the Free Software Foundation.
 *
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace phpMyAdminToolkit.Common
{
	/// <summary>
	/// 
	/// </summary>
	/// <remarks>
	/// Based on this http://www.codeproject.com/KB/recipes/command_line.aspx article of Richard Lopes and on
	/// comments made by BillyZKid. Should contribute regural expression when tested enough.
	/// </remarks>
	public class ParametersBase : IEnumerable<KeyValuePair<string, string>>
	{
		Dictionary<string, string> _store;
		Dictionary<string, string> Store
		{
			get
			{
				if (_store == null)
					_store = new Dictionary<string, string>();

				return _store;
			}
		}

		public ParametersBase(string[] args)
		{
			// ^(?:[-/]?)(?<Name>[^=:]*)(?<EqualityOperator>[=:]?)(?<Quote>['"]?)(?<Value>[^'"]*?)\k<Quote>$
			Regex r = new Regex(phpMyAdminToolkit.Common.Properties.Resources.ParametersRegex);

			foreach (string arg in args)
			{
				Match match = r.Match(arg);
				if (!match.Success)
					throw new ArgumentException("Invalid argument format: " + arg);

				Store.Add(match.Groups["Name"].Value, match.Groups["Value"].Value);
			}
		}

		/// <summary>
		/// Retrieve a parameter value if it exists. 
		/// </summary>
		/// <param name="Param"></param>
		/// <returns></returns>
		/// <remarks>
		/// Overriding C# indexer property.
		/// </remarks>
		public string this[string param]
		{
			get
			{
				return Store[param];
			}
		}

		#region IEnumerable<KeyValuePair<string,string>> Members

		public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
		{
			return Store.GetEnumerator();
		}

		#endregion

		#region IEnumerable Members

		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
		{
			return Store.GetEnumerator();
		}

		#endregion
	}
}
